package com.xxkk.gameCore.net.redis;

import com.ebo.storage.redis.JRedis;
import com.ebo.storage.redis.RedisStorageKey;
import com.xxkk.gameCore.enums.StorageKey;
import com.xxkk.gameCore.global.globalServer.ServerConfig;
import com.xxkk.gameCore.vo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * @author xxkk
 * @version 1.0.0
 * @title GlobalRepo
 * @description <description class purpose>
 * @create 2023/11/11 14:12
 **/
@Repository
public class RoleRepo {
    @Autowired
    private JRedis jRedis;

    private final static String role_id_inc_key_str = "role id inc key str, do not change it";// 玩家id自增键
    private final static String player_platform_inc_key_str = "platform inc key str, do not change it";// 玩家平台id自增键

    private byte[] getRoleIdIncKey() {// roleId自增键字节数组 roleId key
        return RedisStorageKey.getByteArray(role_id_inc_key_str, StorageKey.global_role_id_inc_key.code);
    }

    public long newRoleId() {
        byte[] key = this.getRoleIdIncKey();
        return jRedis.incr(key) + ServerConfig.platformType.code;
    }

    private byte[] getPlatformIdIncKey() {// 平台id自增键字节数组 platform key
        return RedisStorageKey.getByteArray(player_platform_inc_key_str, StorageKey.global_platform_id_inc_key.code);
    }

    public String newPlatformId() {
        byte[] key = this.getPlatformIdIncKey();
        return ServerConfig.platformType.name() + jRedis.incr(key);
    }

    private byte[] getRoleKey(long roleId) {// role key
        return RedisStorageKey.getByteArray(roleId, StorageKey.role_info_key.code);
    }

    public Role getRole(long roleId) {
        byte[] key = getRoleKey(roleId);
        byte[] bytes = this.jRedis.get(key);
        if (bytes == null) {
            return null;
        }
        Role role = new Role();
        role.parseFrom(bytes);
        return role;
    }

    public void saveRole(Role role) {
        byte[] key = getRoleKey(role.getRoleId());
        this.jRedis.set(key, role.build().build().toByteArray());
    }

}
